package com.os.controller;

import cn.hutool.core.util.ObjectUtil;
import com.os.exception.Asserts;
import com.os.ops.Ops;
import com.os.result.Resp;
import com.os.result.ResultCode;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

/**
 * 对象文件操作
 *
 * @author 风亦未止
 * @date 2023/5/1 23:38
 */
@RestController
@RequestMapping("/api/v1/obj")
public class ObjController {
    @Autowired
    private Ops ops;


    @PutMapping("/")
    public Resp put(@RequestParam("file") MultipartFile file) {
        boolean b = ops.putObj(file);
        if (b) {
            return Resp.success(null, "上传成功~");
        }
        return Resp.failed("上传失败~");
    }

    @PutMapping("/v2/{name}")
    public Resp putV2(HttpServletRequest request, @PathVariable("name") String fileName, @RequestHeader String hash,@RequestHeader int length) throws IOException {
        boolean b = ops.putStream(request.getInputStream(), fileName, hash, length);
        if (b) {
            return Resp.success(null, "上传成功~");
        }
        return Resp.failed("上传失败~");
    }

    @GetMapping("/{name}")
    public void get(@PathVariable("name") String name,
                    HttpServletResponse response) throws IOException {
        ServletOutputStream write = response.getOutputStream();
        InputStream source = ops.getObj(name);
        if (ObjectUtil.isNull(source)) {
            Asserts.fail(ResultCode.NOTFOUND);
        }
        IOUtils.copy(source, write);
    }

    @GetMapping("/{name}/{version}")
    public void getByVersion(@PathVariable("name") String name,
                             @PathVariable("version") Integer version,
                             HttpServletResponse response) throws IOException {
        ServletOutputStream write = response.getOutputStream();
        InputStream source = ops.getObjByVersion(name, version);
        if (ObjectUtil.isNull(source)) {
            Asserts.fail(ResultCode.NOTFOUND);
        }
        IOUtils.copy(source, write);
    }

    @GetMapping("/version/{name}")
    public Resp getAllVersion(@PathVariable("name") String name) {
        return ops.getAllVersion(name);
    }

    @DeleteMapping("/{name}")
    public Resp del(@PathVariable("name") String name) {
        boolean b = ops.delObj(name);
        if (b) {
            return Resp.success(null, "删除成功~");
        }
        return Resp.failed("删除失败~");
    }

}
